import useUserStore from "@/store/modules/user";
import axios from "axios";
import { ElMessage } from "element-plus";


const request = axios.create({
  baseURL: import.meta.env.VITE_SERVE,
  headers: {
    "Content-Type": "application/json",
  },
  timeout: 10000,
});

// 可以配合使用Nprogress插件
request.interceptors.request.use(
  (config) => {

    const userStore = useUserStore();

    if (userStore.token) {
      config.headers.token = userStore.token;
    }

    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {

    // 响应返回状态码
    let status = error.response.status;

    switch (status) {
      case 401:
        ElMessage.error(status + ":登录过期，请重新登录");
        break;
      case 403:
        ElMessage.error(status + ":拒绝访问");
        break;
      case 404:
        ElMessage.error(status + ":请求地址出错");
        break;
      case 408:
        ElMessage.error(status + ":请求超时");
        break;
      case 500:
        ElMessage.error(status + ":服务器内部错误");
        break;
      default:
        ElMessage.error(status + ":网络异常");
    }

    return Promise.reject(error);
  }
);

export default request;